package com.osce.framework.web.service;

import com.osce.common.core.entity.AjaxResult;
import com.osce.common.core.entity.entity.SysUser;
import com.osce.common.core.entity.model.LoginUser;
import com.osce.common.exception.ServiceException;
import com.osce.interfaces.face.IFaceListService;
import com.osce.interfaces.system.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


/**
 * 用户人脸验证处理
 *
 * @author ruoyi
 */
@Service
public class UserFaceDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserFaceDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IFaceListService faceListService;

    @Autowired
    private SysPermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String base64) throws UsernameNotFoundException {
        AjaxResult compareResult = faceListService.faceCompareBase64(base64);
        if (!compareResult.get("code").equals(200)) {
            throw new ServiceException(compareResult.get("msg").toString());
        }
        return createLoginUser(userService.selectUserById((Long) compareResult.get("data")));
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }
}
